package com.gome.extract.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.mongodb.Mongo;

public class AppConfiguer {
	private static Logger logger = null;
	
	private static final String path = getConfDir() + "db.properties";
	public static final String pluginTaskIDPrefix = "PTask-";
	public static Mongo flowCrawlConfigMongo = null;
	public static Mongo ssMongo = null;
	
	public static String getConfDir() {
		return System.getProperty("user.dir") + "/config/";
	}
	
	public static String getValueByKey(String key) {
		Properties pps = new Properties();
		InputStream in;
		try {
			in = new BufferedInputStream (new FileInputStream(path));
			pps.load(in);
			String value = pps.getProperty(key);
			in.close();
			return value;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(getTrace(e));
			return null;
		}
	}
	
	public static String getStringByKey(String key) {
		return getValueByKey(key);
	}
	
	public static int getIntByKey(String key) {
		Properties pps = new Properties();
		InputStream in;
		try {
			in = new BufferedInputStream (new FileInputStream(path));
			pps.load(in);
			String value = pps.getProperty(key);
			in.close();
			return Integer.parseInt(value, 10);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(getTrace(e));
			return 0;
		}
	}
	
	public static void initLog4j() {
		 String filePath =  AppConfiguer.getConfDir() + "log4j.properties";
		 String logPath = AppConfiguer.getStringByKey("log_path");
		 String logLevel = AppConfiguer.getStringByKey("log_level");
		 
		 Properties props = new Properties();
		 props.setProperty("log4j.rootLogger", logLevel + ", A");
		 props.setProperty("log4j.appender.A", "org.apache.log4j.RollingFileAppender");
		 props.setProperty("log4j.appender.A.File", logPath);
		 props.setProperty("log4j.appender.A.MaxFileSize", "20480KB");
		 props.setProperty("log4j.appender.A.MaxBackupIndex", "1");
		 props.setProperty("log4j.appender.A.layout", "org.apache.log4j.PatternLayout");
		 props.setProperty("log4j.appender.A.layout.ConversionPattern", "%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n");
		 
		 PropertyConfigurator.configure(props);//装入log4j配置信息
		 
		 logger = Logger.getLogger(AppConfiguer.class);
	}
	
	public static String getTrace(Throwable t) {
        StringWriter stringWriter= new StringWriter();
        PrintWriter writer= new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer= stringWriter.getBuffer();
        return buffer.toString();
    }
}
